package com.efun.center.http.service;

import com.alibaba.fastjson.JSONObject;
import com.efun.center.http.config.ParamInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Service("sendMailService")
public class SendMailService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String username;

    public void sendErrorEmail(ParamInfo paramInfo, String area, String fullUrl, String result, String body) {
        if (paramInfo.isIgnoreErr()) {
            return;
        }

        String threadNo = Thread.currentThread().getName();
        Thread thread = new Thread() {

            public void run() {
                String subject = "";
                String content = "AREA : " + area + "<br><br>";
                content += "URL : " + fullUrl + "<br><br>";
                if (!StringUtils.isEmpty(body)) {
                    content += "CONTENT-TYPE : " + paramInfo.getContentType() + "<br><br>";
                    content += "BODY : " + body + "<br><br>";
                    logger.info("BODY : " + body);
                }
                try {
                    InetAddress address = InetAddress.getLocalHost();
                    content += "MORE : [主机 : " + address.getHostName() + ", IP : " + address.getHostAddress() + ", 线程 : " + threadNo + "]<br><br>";
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                if (result.toUpperCase().contains("<!DOCTYPE HTML")) {
                    content += "RESULT : " + result + "<br><br>";
                    sendMail(paramInfo.getMethodMapper().getEmail(), "服务器内部错误", content);
                } else {
                    try {
                        JSONObject json = JSONObject.parseObject(result);
                        if (null == json || json.get("code") == null || StringUtils.isEmpty(json.getString("code"))) {
                            subject = "接口方未返回数据";
                            content += "RESULT : " + result + "<br><br>";
                        } else {
                            String code = json.getString("code");
                            if (!code.equals("1000") && !code.equals("0000") && !code.equals("e1000")) {
                                subject = "接口方执行失败";
                                content += "RESULT : " + result + "<br><br>";
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();

                        subject = "接口方返回格式不正确";
                        content += "RESULT : " + result + "<br><br>";
                    } finally {
                        if (!StringUtils.isEmpty(subject)) {
                            sendMail(paramInfo.getMethodMapper().getEmail(), subject, content);
                        }
                    }
                }
            }

        };
        thread.setPriority(Thread.MIN_PRIORITY);
        thread.start();
    }

    private void sendMail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(new InternetAddress(username, "后台异常上报器(请勿直接回复此邮件)", "UTF-8"));
            String[] tos = new String[2];
            tos[0] = "itda@efun.com";
            tos[1] = to != null ? to : "";
            helper.setTo(tos);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("邮件发送失败", e.getMessage());
        }
    }

}
